// 引入必要的库
const CryptoJS = require('crypto-js');
const uuidv4 = require('uuid').v4;

export function generateHeaders(appid: any, capabilityname: any, appKey: any) {
    // 生成csid
    const paddingLength = 24 - capabilityname.length;
    const padding = '0'.repeat(paddingLength);
    const csid = `${appid}${capabilityname}${padding}${uuidv4().replace(/-/g, '')}`;

    // 构造X-Server-Param
    const xServerParamData = {
        appid: appid,
        csid: csid
    };
    const xServerParamString = JSON.stringify(xServerParamData);
    const xServerParam = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(xServerParamString));
    // 替换 '+' 和 '/' 为 '-' 和 '_'，并去掉可能的 '=' 填充
    xServerParam
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');

    // 获取当前时间戳
    const curtime = Math.floor(Date.now() / 1000);

    // 构造校验和
    const checksumStr = `${appKey}${curtime}${xServerParam}`;
    const checkSum = CryptoJS.MD5(checksumStr).toString();

    // 构造headers对象
    const headers = {
        'X-Server-Param': xServerParam,
        'X-CurTime': curtime.toString(),
        'X-CheckSum': checkSum,
        Authorization: 'Bearer ZTNkNjY5YTUzNDZjMjUzMzpjaGF0YmlA5rWL6K-V6LSm5Y-3OnVhdDo0MmVhMDMxOTJhNjM4YmNk'
    };

    return headers;
}

export function generateHeadersChat(appid: any, capabilityname: any, appKey: any) {
    // 生成csid
    let csid = appid + capabilityname;
    const paddingLength = 24 - capabilityname.length;
    if (paddingLength > 0) {
        csid += '0'.repeat(paddingLength);
    }
    const uuid = uuidv4().replace(/-/g, '');
    csid += uuid;

    // 生成x_server_param
    const serverParam = {
        appid: appid,
        csid: csid
    };
    const xServerParam = btoa(JSON.stringify(serverParam))
        .replace(/\+/g, '-') // 将 '+' 替换为 '-'
        .replace(/\//g, '_') // 将 '/' 替换为 '_'
        .replace(/=+$/, ''); // 去掉结尾的 '='

    // 生成curtime
    const curtime = Math.floor(Date.now() / 1000);

    // 生成checkSum
    const dataToHash = `${appKey}${curtime}${xServerParam}`;
    const checkSum = CryptoJS.MD5(dataToHash).toString();

    // 构造headers
    const headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'X-Server-Param': xServerParam,
        'X-CurTime': curtime.toString(),
        'X-CheckSum': checkSum,
        Authorization: 'Bearer ZTNkNjY5YTUzNDZjMjUzMzpjaGF0YmlA5rWL6K-V6LSm5Y-3OnVhdDo0MmVhMDMxOTJhNjM4YmNk'
    };

    return headers;
}
